package mk.edu.ii.navigatemacedonia;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class ServiceConnect {
	ArrayList<Site> sites=new ArrayList<Site>();
	View v;
	Context context;
	public static String SITE_NAME = "SiteName";
	public static String SITE_DESCRIPTION = "SiteDescription";
	public static String SITE_CATEGORY = "SiteCategory";
	public static String SITE_IMAGE = "SiteImage";
	public static String SITE_LONGITUDE = "SiteLongitude";
	public static String SITE_LATITUDE = "SiteLatitude";
	public static String SITE_SUBCATEGORY = "SiteSubCategory";
	public static String SITE_RATING = "SiteRating";
	//private static final String URL = "@string/Service_location";
	private static final String URL = "http://192.168.1.106/SiteService/Service.svc/GetData?";
	
	ArrayList<Site> getSitesFromService(Context context, Double longitude, Double latitude, Integer radius, String category) {
		// inicijalizacija na pogled vo slucaj da treba da se prikaze na ekran 
		// nekoe izvestuvanje
		this.context = context;
		
		// konektiranje na servisot so soodvetnoto URL
		
		return connect(getURL(longitude, latitude, radius, category));
		}
	
	//connecting to service and put information into ArrayList of Sites
	public ArrayList<Site> connect(String url) {
		//inicijalizacija na http GET metod
		HttpGet httpget = new HttpGet(url);
		
		//Parametri za Timeout
		HttpParams httpParameters = new BasicHttpParams();
		// Set the timeout in milliseconds until a connection is established.
		int timeoutConnection = 3000;
		HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
		// Set the default socket timeout (SO_TIMEOUT) 
		// in milliseconds which is the timeout for waiting for data.
		int timeoutSocket = 5000;
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
		
		// inicijalizacija na http client
		HttpClient httpclient = new DefaultHttpClient(httpParameters);
				
		// deklaracija na http response(ona sto treba da go primime)
		HttpResponse response;
		try {
			
			// povikuvanje na GET metodot
			response = httpclient.execute(httpget);
			
			Log.i("REST:Response Status line", response.getStatusLine().toString());

			HttpEntity entity = response.getEntity();
			//TextView b=(TextView)findViewById(R.id.text);
			
			if (entity != null) {

				InputStream instream = entity.getContent();
				String result = convertStreamToString(instream);
				
				Log.i("REST: result", result);
				
				JSONObject json = new JSONObject(result);
				JSONArray sitesArray = new JSONArray();
				sitesArray = json.getJSONArray("sites");
				//Log.i("REST", "<jsonobject>\n" + json.toString()+ "\n</jsonobject>");

				// Parsing								
				for (int i = 0; i < sitesArray.length(); i++) {
					//sitesArray.getJSONObject(i);
					//sites.add(object)
					sites.add(this.jsonToSite(sitesArray.getJSONObject(i)));
					
				}
				//b.setText(sites.get(1).getSiteLongitude().toString());
				json.put("sample key", "sample value");
				Log.i("REST", "<jsonobject>\n" + json.toString()
						+ "\n</jsonobject>");

				instream.close();
			}
		} catch (JSONException e) {
		// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			String msg = "Application can not connect to service";
    		int duration = Toast.LENGTH_SHORT;
    		Toast toast = Toast.makeText(context, msg, duration);
    		toast.show();
			e.printStackTrace();
			return null;
		} catch(Exception e){
        	String msg = "Application can not connect to service";
    		int duration = Toast.LENGTH_SHORT;
    		Toast toast = Toast.makeText(context, msg, duration);
    		toast.show();
    		return null;
        } 
		return sites;
	}
    
	// converting HTTP respond stream from service to String 
    private static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
    
    // Constructing full URL
    public String getURL(Double longitude, Double latitude, Integer radius, String category ){
    	String url;
    	
    	//http://192.168.1.106/SiteService/Service.svc/GetData?param1=1&param2=1&param3=1&param4=1
    	url = URL + "param1="+longitude.toString()
    			+ "&param2="+latitude.toString()
    			+ "&param3="+radius.toString()
    			+ "&param4="+category;
    	
		//int duration = Toast.LENGTH_SHORT;
		//Toast toast = Toast.makeText(v.getContext(), url, duration);
		//toast.show();
    	return url;
    }
    
    // map json object to Site object
    public Site jsonToSite(JSONObject json){
    	String name = json.optString(SITE_NAME);
		String description = json.optString(SITE_DESCRIPTION);
		String image = json.optString(SITE_IMAGE);
		String category = json.optString(SITE_CATEGORY);
		String longitude = json.optString(SITE_LONGITUDE);
		String latitude = json.optString(SITE_LATITUDE);
		String subCategory = json.optString(SITE_SUBCATEGORY);
		String rating = json.optString(SITE_RATING);
    	Site site = new Site(name, description, category, image
    			, longitude, latitude, subCategory, rating);
    	return site;
    }
    
    
}
